package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.*;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/index")
@CrossOrigin
@Slf4j
public class SysIndexController {
    @Autowired
    private IYddCateService yddCateService;

    @Autowired
    private IYddAdvposService yddAdvposService;

    @Autowired
    private IYddTagService yddTagService;

    @Autowired
    private IYddArticleService yddArticleService;

    @Autowired
    private IYddAdvimgService yddAdvimgService;

    @Autowired
    private IYddUserService yddUserService;

    @Autowired
    private IYddUserDataService yddUserDataService;

    @Autowired
    private IYddLinkService yddLinkService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService sysConfigService;

    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {
        log.info("登陆用户：{}", sysUser.toString());

        String loginName = sysUser.getLoginName();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLoginName, loginName);
        SysUser one = sysUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        } else if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        String password = sysUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
            String roleId = one.getRoleId()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("userId", one.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }


    @GetMapping("/getConfig")
    public R systemConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return new R(map, "", 0);

    }

    @PostMapping("/profile")
    public R profile(HttpServletRequest request) {
        String token = request.getHeader("x-token");

        Claims claims = JwtUtils.getClaims(token);
        Long userId = Long.valueOf((String) claims.get("userId"));

        log.info("用户id:{}", userId);
        return sysUserService.profile(userId);
    }

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    @GetMapping("/index")
    public ResultData index(){
        //初始化首页数据
        IndexDto indexDto = new IndexDto();
        //设置所有分类列表
        indexDto.setAllCate(yddCateService.list());
        //设置所有标签对象
        indexDto.setAllTag(yddTagService.list());
        //设置所有友情链接
        indexDto.setAllLink(yddLinkService.list());
        //设置轮播图
        LambdaQueryWrapper<YddAdvimg> yddAdvimgLQW = new LambdaQueryWrapper<>();
        yddAdvimgLQW.eq(YddAdvimg::getAdvimgpos,15); //15 首页的轮播图
        indexDto.setBanner(yddAdvimgService.list(yddAdvimgLQW));
        //设置侧边栏图
        yddAdvimgLQW.clear(); //清除条件
        yddAdvimgLQW.eq(YddAdvimg::getAdvimgpos,14); //14 首页右侧三张广告图
        indexDto.setSideBanner(yddAdvimgService.list(yddAdvimgLQW));
        //设置详情广告图
        yddAdvimgLQW.clear(); //清除条件
        yddAdvimgLQW.eq(YddAdvimg::getAdvimgpos,13); //15 详情页标题下面的广告图
        indexDto.setShowBanner(yddAdvimgService.list(yddAdvimgLQW));
        //设置配置数据
        Map<String,Object> config = new HashMap<>(1);
        List<SysConfig> sysConfigList=sysConfigService.list();
        //初始化配置类列表
        List<ConfigDto> configDtoList = new ArrayList<>();
        for (SysConfig sysConfig : sysConfigList) {
            ConfigDto configDto = new ConfigDto();
            //复制初始值
            BeanUtils.copyProperties(sysConfig,configDto);
            List<ConfigValueDto> configValueDtoList = new ArrayList<>();
            String configValue=sysConfig.getConfigValue();
            //判断 configvalue 是否为空 不为空 则切割字符串
            if(configValue != null && configValue.length() != 0){
                //切割 是=1&否=2
                String[] split=sysConfig.getConfigValue().split("&");

                for (String s : split) {
                    //将切割的数据 封装到 configValueDto中
                    ConfigValueDto configValueDto = new ConfigValueDto();
                    String[] split1=s.split("=");
                    configValueDto.setLabel(split1[0]);
                    configValueDto.setLabel(split1[1]);
                    //将封装好的数据 添加到集合中
                    configValueDtoList.add(configValueDto);
                }
            }


            configDto.setConfig_value(configValueDtoList);
            configDtoList.add(configDto);
        }

        config.put("allData",configDtoList);
        indexDto.setConfig(config);
        return ResultData.ok("",indexDto);
    }


    /*@GetMapping("/index")
    public String index(HttpServletResponse response) throws IOException {
        String msg = "{\"errno\":0,\"errmsg\":\"\",\"data\":{\"allCate\":[{\"id\":85163170,\"catename\":\"123\",\"icon\":\"123\",\"sort_num\":123,\"default_data\":\"0\"},{\"id\":3,\"catename\":\"时政\",\"icon\":\"fa-university\",\"sort_num\":12,\"default_data\":\"1\"},{\"id\":21940161,\"catename\":\"时政\",\"icon\":\"啊哇哇哇\",\"sort_num\":12,\"default_data\":\"0\"},{\"id\":21940162,\"catename\":\"时尚\",\"icon\":\"swwa\",\"sort_num\":11,\"default_data\":\"0\"},{\"id\":8,\"catename\":\"科技\",\"icon\":\"fa-rocket\",\"sort_num\":10,\"default_data\":\"1\"},{\"id\":9,\"catename\":\"时尚\",\"icon\":\"fa-envira\",\"sort_num\":10,\"default_data\":\"1\"},{\"id\":60,\"catename\":\"11\",\"icon\":\"222\",\"sort_num\":10,\"default_data\":\"0\"},{\"id\":6466970,\"catename\":\"666\",\"icon\":\"222\",\"sort_num\":10,\"default_data\":\"0\"},{\"id\":6,\"catename\":\"汽车\",\"icon\":\"fa-car\",\"sort_num\":9,\"default_data\":\"1\"},{\"id\":7,\"catename\":\"段子\",\"icon\":\"fa-quora\",\"sort_num\":9,\"default_data\":\"1\"},{\"id\":4,\"catename\":\"图片\",\"icon\":\"fa-file-photo-o\",\"sort_num\":8,\"default_data\":\"1\"},{\"id\":5,\"catename\":\"娱乐\",\"icon\":\"fa-commenting\",\"sort_num\":7,\"default_data\":\"1\"}],\"config\":{\"list\":[{\"name\":\"基础配置\",\"key\":\"base\",\"children\":[{\"name\":\"站点配置\",\"data\":[{\"id\":24,\"group_value\":\"站点配置\",\"tab_value\":\"base\",\"attr_key\":\"site_name\",\"attr_name\":\"站点名称\",\"attr_value\":\"优点达资讯-发现有意思的事儿\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"[{\\\"required\\\":true,\\\"message\\\":\\\"站点名必须\\\",\\\"trigger\\\":\\\"blur\\\"}]\",\"placeholder\":\"请输入站点名称\",\"can_delete\":0,\"sort_num\":1,\"default_data\":\"1\"},{\"id\":25,\"group_value\":\"站点配置\",\"tab_value\":\"base\",\"attr_key\":\"site_link\",\"attr_name\":\"站点链接\",\"attr_value\":\"http://122.51.249.55:8060/home\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入站点链接\",\"can_delete\":0,\"sort_num\":2,\"default_data\":\"1\"},{\"id\":26,\"group_value\":\"站点配置\",\"tab_value\":\"base\",\"attr_key\":\"site_keywords\",\"attr_name\":\"站点关键字\",\"attr_value\":\"优点达资讯系统，优点达资讯系统优点达资讯系统优点达资讯系统\",\"del_flag\":0,\"type\":3,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入站点关键字\",\"can_delete\":0,\"sort_num\":3,\"default_data\":\"1\"},{\"id\":125,\"group_value\":\"站点配置\",\"tab_value\":\"base\",\"attr_key\":\"close_website\",\"attr_name\":\"是否关闭网站\",\"attr_value\":\"1\",\"del_flag\":0,\"type\":4,\"config_value\":[{\"label\":\"是\",\"value\":\"1\"},{\"label\":\"否\",\"value\":\"2\"}],\"validator\":\"\",\"placeholder\":\"请选择\",\"can_delete\":0,\"sort_num\":4,\"default_data\":\"1\"}]},{\"name\":\"底部信息\",\"data\":[{\"id\":53,\"group_value\":\"底部信息\",\"tab_value\":\"base\",\"attr_key\":\"copy_code\",\"attr_name\":\"备案号\",\"attr_value\":\"皖-备88888888\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入备案号\",\"can_delete\":0,\"sort_num\":5,\"default_data\":\"1\"},{\"id\":54,\"group_value\":\"底部信息\",\"tab_value\":\"base\",\"attr_key\":\"copy_info\",\"attr_name\":\"版权信息\",\"attr_value\":\"优点达版权所有，翻版必究\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入版权信息\",\"can_delete\":0,\"sort_num\":6,\"default_data\":\"1\"},{\"id\":55,\"group_value\":\"底部信息\",\"tab_value\":\"base\",\"attr_key\":\"phone\",\"attr_name\":\"联系方式\",\"attr_value\":\"hewu1122@163.com\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入联系方式\",\"can_delete\":0,\"sort_num\":6,\"default_data\":\"1\"},{\"id\":56,\"group_value\":\"底部信息\",\"tab_value\":\"base\",\"attr_key\":\"copy_url\",\"attr_name\":\"备案链接地址\",\"attr_value\":\"http://www.baidu.com\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入备案链接地址\",\"can_delete\":0,\"sort_num\":8,\"default_data\":\"1\"}]},{\"name\":\"其他配置\",\"data\":[{\"id\":57,\"group_value\":\"其他配置\",\"tab_value\":\"base\",\"attr_key\":\"black_ip\",\"attr_name\":\"黑名单IP\",\"attr_value\":\"\",\"del_flag\":0,\"type\":3,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"黑名单IP，用逗号隔开，注意英文半角逗号\",\"can_delete\":0,\"sort_num\":9,\"default_data\":\"1\"}]}]},{\"name\":\"系统设置\",\"key\":\"system\",\"children\":[{\"name\":\"管理系统配置\",\"data\":[{\"id\":79,\"group_value\":\"管理系统配置\",\"tab_value\":\"system\",\"attr_key\":\"system_name\",\"attr_name\":\"系统名称\",\"attr_value\":\"优点达资讯系统\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"显示在title和logo右侧文字内容\",\"can_delete\":0,\"sort_num\":0,\"default_data\":\"1\"},{\"id\":80,\"group_value\":\"管理系统配置\",\"tab_value\":\"system\",\"attr_key\":\"system_logo\",\"attr_name\":\"系统logo\",\"attr_value\":\"static/admin/image/logo.png\",\"del_flag\":0,\"type\":9,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"显示在左上角位置，大小建议200*200\",\"can_delete\":0,\"sort_num\":0,\"default_data\":\"1\"},{\"id\":81,\"group_value\":\"管理系统配置\",\"tab_value\":\"system\",\"attr_key\":\"web_ico\",\"attr_name\":\"网页图标\",\"attr_value\":\"static/admin/image/favicon.ico\",\"del_flag\":0,\"type\":9,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"网页favicon文件，ico类型，建议64*64\",\"can_delete\":0,\"sort_num\":0,\"default_data\":\"1\"},{\"id\":77,\"group_value\":\"管理系统配置\",\"tab_value\":\"system\",\"attr_key\":\"login_title\",\"attr_name\":\"登录标题\",\"attr_value\":\"优点达资讯系统\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"显示在登录表单上面的内容\",\"can_delete\":0,\"sort_num\":10,\"default_data\":\"1\"},{\"id\":78,\"group_value\":\"管理系统配置\",\"tab_value\":\"system\",\"attr_key\":\"login_bg\",\"attr_name\":\"登录页背景图\",\"attr_value\":\"static/admin/image/loginbg.png\",\"del_flag\":0,\"type\":9,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"建议1920*1080尺寸\",\"can_delete\":0,\"sort_num\":11,\"default_data\":\"1\"}]}]},{\"name\":\"其他设置\",\"key\":\"custom\",\"children\":[{\"name\":\"通知公告\",\"data\":[{\"id\":2,\"group_value\":\"通知公告\",\"tab_value\":\"custom\",\"attr_key\":\"notic_title\",\"attr_name\":\"公告标题\",\"attr_value\":\"感谢广告网网友\",\"del_flag\":0,\"type\":1,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入公告标题\",\"can_delete\":0,\"sort_num\":10,\"default_data\":\"1\"},{\"id\":78017,\"group_value\":\"通知公告\",\"tab_value\":\"custom\",\"attr_key\":\"notic_content\",\"attr_name\":\"通知内容\",\"attr_value\":\"非常感谢广告网网友对本网站的关注和喜爱，如果有任何的问题，欢迎提供宝贵意见，练习方式参见网站底部邮箱。\",\"del_flag\":0,\"type\":3,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"请输入内容\",\"can_delete\":0,\"sort_num\":10,\"default_data\":\"1\"}]},{\"name\":\"前台图片\",\"data\":[{\"id\":44,\"group_value\":\"前台图片\",\"tab_value\":\"custom\",\"attr_key\":\"loginreg_bg\",\"attr_name\":\"登录/注册页背景\",\"attr_value\":\"\",\"del_flag\":0,\"type\":9,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"尺寸 200*200\",\"can_delete\":0,\"sort_num\":10,\"default_data\":\"1\"},{\"id\":239,\"group_value\":\"前台图片\",\"tab_value\":\"custom\",\"attr_key\":\"web_img\",\"attr_name\":\"前台logo\",\"attr_value\":\"upload/images/20211101/1635766045081.jpg\",\"del_flag\":0,\"type\":9,\"config_value\":\"\",\"validator\":\"\",\"placeholder\":\"尺寸168*70，透明，白色\",\"can_delete\":0,\"sort_num\":10,\"default_data\":\"1\"}]}]}],\"allData\":[{\"id\":81,\"attr_key\":\"web_ico\",\"attr_value\":\"static/admin/image/favicon.ico\",\"validator\":\"\",\"config_value\":\"\",\"type\":9},{\"id\":80,\"attr_key\":\"system_logo\",\"attr_value\":\"static/admin/image/logo.png\",\"validator\":\"\",\"config_value\":\"\",\"type\":9},{\"id\":79,\"attr_key\":\"system_name\",\"attr_value\":\"优点达资讯系统\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":24,\"attr_key\":\"site_name\",\"attr_value\":\"优点达资讯-发现有意思的事儿\",\"validator\":\"[{\\\"required\\\":true,\\\"message\\\":\\\"站点名必须\\\",\\\"trigger\\\":\\\"blur\\\"}]\",\"config_value\":\"\",\"type\":1},{\"id\":25,\"attr_key\":\"site_link\",\"attr_value\":\"http://122.51.249.55:8060/home\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":26,\"attr_key\":\"site_keywords\",\"attr_value\":\"优点达资讯系统，优点达资讯系统优点达资讯系统优点达资讯系统\",\"validator\":\"\",\"config_value\":\"\",\"type\":3},{\"id\":125,\"attr_key\":\"close_website\",\"attr_value\":\"1\",\"validator\":\"\",\"config_value\":[{\"label\":\"是\",\"value\":\"1\"},{\"label\":\"否\",\"value\":\"2\"}],\"type\":4},{\"id\":53,\"attr_key\":\"copy_code\",\"attr_value\":\"皖-备88888888\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":54,\"attr_key\":\"copy_info\",\"attr_value\":\"优点达版权所有，翻版必究\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":55,\"attr_key\":\"phone\",\"attr_value\":\"hewu1122@163.com\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":56,\"attr_key\":\"copy_url\",\"attr_value\":\"http://www.baidu.com\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":57,\"attr_key\":\"black_ip\",\"attr_value\":\"\",\"validator\":\"\",\"config_value\":\"\",\"type\":3},{\"id\":77,\"attr_key\":\"login_title\",\"attr_value\":\"优点达资讯系统\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":2,\"attr_key\":\"notic_title\",\"attr_value\":\"感谢广告网网友\",\"validator\":\"\",\"config_value\":\"\",\"type\":1},{\"id\":44,\"attr_key\":\"loginreg_bg\",\"attr_value\":\"\",\"validator\":\"\",\"config_value\":\"\",\"type\":9},{\"id\":239,\"attr_key\":\"web_img\",\"attr_value\":\"upload/images/20211101/1635766045081.jpg\",\"validator\":\"\",\"config_value\":\"\",\"type\":9},{\"id\":78017,\"attr_key\":\"notic_content\",\"attr_value\":\"非常感谢广告网网友对本网站的关注和喜爱，如果有任何的问题，欢迎提供宝贵意见，练习方式参见网站底部邮箱。\",\"validator\":\"\",\"config_value\":\"\",\"type\":3},{\"id\":78,\"attr_key\":\"login_bg\",\"attr_value\":\"static/admin/image/loginbg.png\",\"validator\":\"\",\"config_value\":\"\",\"type\":9}]},\"allTag\":[{\"id\":1,\"tagname\":\"搞笑1\",\"default_data\":\"1\"},{\"id\":2,\"tagname\":\"玻璃新\",\"default_data\":\"1\"},{\"id\":9,\"tagname\":\"军事\",\"default_data\":\"0\"},{\"id\":14,\"tagname\":\"二次元\",\"default_data\":\"1\"},{\"id\":15,\"tagname\":\"摄影\",\"default_data\":\"1\"},{\"id\":16,\"tagname\":\"汉服\",\"default_data\":\"1\"},{\"id\":17,\"tagname\":\"文字控\",\"default_data\":\"1\"},{\"id\":18,\"tagname\":\"诗歌\",\"default_data\":\"1\"},{\"id\":19,\"tagname\":\"手机控\",\"default_data\":\"1\"},{\"id\":20,\"tagname\":\"懒癌患者\",\"default_data\":\"1\"},{\"id\":21,\"tagname\":\"资深吃货\",\"default_data\":\"1\"},{\"id\":22,\"tagname\":\"军事\",\"default_data\":\"1\"},{\"id\":23,\"tagname\":\"娱乐\",\"default_data\":\"1\"},{\"id\":28,\"tagname\":\"科技\",\"default_data\":\"1\"},{\"id\":88,\"tagname\":\"12331123123\",\"default_data\":\"0\"},{\"id\":977868,\"tagname\":\"水\",\"default_data\":\"0\"}],\"allLink\":[{\"id\":4,\"title\":\"ikun\",\"url\":\"ikunikun\",\"des\":\"么么哒\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"0\"},{\"id\":17,\"title\":\"12221\",\"url\":\"888888\",\"des\":\"98987955\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"0\"},{\"id\":36,\"title\":\"\",\"url\":\"https://www.liepin.com/\",\"des\":\"猎聘网\",\"img\":\"upload/images/20211101/1635758116348.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":37,\"title\":\"\",\"url\":\"https://www.360.cn/\",\"des\":\"360\",\"img\":\"upload/images/20211101/1635758101991.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":38,\"title\":\"\",\"url\":\"https://www.mi.com/\",\"des\":\"小米\",\"img\":\"upload/images/20211101/1635758076821.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":40,\"title\":\"\",\"url\":\"http://www.163.com\",\"des\":\"网易\",\"img\":\"upload/images/20211101/1635758063917.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":41,\"title\":\"\",\"url\":\"https://www.1688.com/\",\"des\":\"阿里巴巴\",\"img\":\"upload/images/20211101/1635758024734.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":42,\"title\":\"\",\"url\":\"http://www.zj.qq.com\",\"des\":\"腾讯大浙网\",\"img\":\"upload/images/20211101/1635758049016.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":43,\"title\":\"\",\"url\":\"http://www.china-yintai.com/\",\"des\":\"银泰商业\",\"img\":\"upload/images/20211101/1635758011257.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":44,\"title\":\"\",\"url\":\"http://www.weibo.com\",\"des\":\"新浪微博\",\"img\":\"upload/images/20211101/1635757995478.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":45,\"title\":\"\",\"url\":\"http://v.qq.com\",\"des\":\"腾讯视频\",\"img\":\"upload/images/20211101/1635757978737.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":46,\"title\":\"\",\"url\":\"http://www.ganji.com\",\"des\":\"赶集网\",\"img\":\"upload/images/20211101/1635757963837.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":47,\"title\":\"\",\"url\":\"http://www.58.com\",\"des\":\"58同城\",\"img\":\"upload/images/20211101/1635757950706.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":48,\"title\":\"\",\"url\":\"http://www.baidu.com\",\"des\":\"百度一下\",\"img\":\"upload/images/20211101/1635757934567.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":49,\"title\":\"淘宝网\",\"url\":\"http://www.taobao.com\",\"des\":\"淘宝网\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":50,\"title\":\"京东购物商城\",\"url\":\"http://www.jd.com\",\"des\":\"京东购物商城\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":51,\"title\":\"苏宁易购\",\"url\":\"https://www.suning.com/\",\"des\":\"苏宁易购\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":52,\"title\":\"百度地图\",\"url\":\"https://map.baidu.com/\",\"des\":\"百度地图\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":53,\"title\":\"爱奇艺\",\"url\":\"https://www.iqiyi.com/\",\"des\":\"爱奇艺\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":54,\"title\":\"东方财富\",\"url\":\"http://www.eastmoney.com/\",\"des\":\"东方财富\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":55,\"title\":\"携程网\",\"url\":\"https://www.ctrip.com/\",\"des\":\"携程网\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":56,\"title\":\"虎牙直播\",\"url\":\"https://www.huya.com/\",\"des\":\"虎牙直播\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":57,\"title\":\"网易云音乐\",\"url\":\"https://music.163.com/\",\"des\":\"网易云音乐\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":58,\"title\":\"优酷网\",\"url\":\"https://www.youku.com/\",\"des\":\"优酷网\",\"img\":\"\",\"type\":\"1\",\"default_data\":\"1\"},{\"id\":59,\"title\":\"7k7游戏\",\"url\":\"http://www.7k7k.com/\",\"des\":\"7k7游戏\",\"img\":\"upload/images/20230325/1679738363690.png\",\"type\":\"2\",\"default_data\":\"1\"},{\"id\":73427,\"title\":\"\",\"url\":\"333333333339999999\",\"des\":\"33333333333333333333333333333\",\"img\":\"upload/images/20230326/1679838278006.jpg\",\"type\":\"2\",\"default_data\":\"0\"},{\"id\":73428,\"title\":\"333333\",\"url\":\"33333\",\"des\":\"33333\",\"img\":\"upload/images/20230326/1679831972441.jpg\",\"type\":\"1\",\"default_data\":\"0\"},{\"id\":73429,\"title\":\"咔咔咔222255555555\",\"url\":\"3333柔柔弱弱\",\"des\":\"333339999999999999999柔柔弱弱\",\"img\":\"upload/images/20230326/1679831972441.jpg\",\"type\":\"1\",\"default_data\":\"0\"}],\"banner\":[{\"id\":2344,\"advimglink\":\"http://www.jd.com\",\"advimgdesc\":\"无爱无伤，万寿无疆\",\"advimgsrc\":\"upload/images/20211101/1635756787611.jpg\"},{\"id\":449990,\"advimglink\":\"123\",\"advimgdesc\":\"只有让自己变得强大，才能无所畏惧\",\"advimgsrc\":\"upload/images/20211101/1635756669674.jpeg\"},{\"id\":449991,\"advimglink\":\"http://www.jd.com\",\"advimgdesc\":\"不是每次微笑都证明我很快乐\",\"advimgsrc\":\"upload/images/20211101/1635756750804.jpeg\"}],\"sideBanner\":[{\"id\":5,\"advimglink\":\"http://www.taobao.com\",\"advimgdesc\":\"开学那点事儿\",\"advimgsrc\":\"upload/images/20211101/1635756021202.jpg\"},{\"id\":6,\"advimglink\":\"http://www.jd.com\",\"advimgdesc\":\"独享云虚拟主机\",\"advimgsrc\":\"upload/images/20211101/1635756052798.jpg\"},{\"id\":449987,\"advimglink\":\"http://www.baidu.com\",\"advimgdesc\":\"全民云计划\",\"advimgsrc\":\"upload/images/20211101/1635755984319.jpg\"}],\"showBanner\":[{\"id\":32,\"advimglink\":\"kunkun.com\",\"advimgdesc\":\"kunkun\",\"advimgsrc\":\"upload/images/20230326/1679820166877.jpg\"},{\"id\":449988,\"advimglink\":\"htttp://www.baidu.com\",\"advimgdesc\":\"云服务器降破底价\",\"advimgsrc\":\"upload/images/20211101/1635756170903.jpg\"},{\"id\":449989,\"advimglink\":\"http://www.jd.com\",\"advimgdesc\":\"领取阿里云优惠券\",\"advimgsrc\":\"upload/images/20211101/1635756202043.png\"},{\"id\":449993,\"advimglink\":\"535\",\"advimgdesc\":\"3344\",\"advimgsrc\":\"upload/images/20230326/1679800264175.jpg\"},{\"id\":449994,\"advimglink\":\"535\",\"advimgdesc\":\"3344\",\"advimgsrc\":\"upload/images/20230326/1679801173321.png\"},{\"id\":28631830,\"advimglink\":\"98989898\",\"advimgdesc\":\"kkkkk\",\"advimgsrc\":\"upload/images/20230326/1679823326338.jpg\"},{\"id\":47320855,\"advimglink\":\"9999999999999999999999\",\"advimgdesc\":\"999999999999999999999\",\"advimgsrc\":\"upload/images/20230326/1679823883749.jpg\"},{\"id\":78596761,\"advimglink\":\"热热11111\",\"advimgdesc\":\"哈哈哈哈\",\"advimgsrc\":\"upload/images/20230326/1679838107110.jpg\"}]}}";
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(msg);

        return null;
    }*/


    @GetMapping("/hot")
    public R hot(){

        LambdaQueryWrapper<YddArticle> yddArticleLQW = new LambdaQueryWrapper<>();
        //设置热点文章条件
        yddArticleLQW.eq(YddArticle::getIshot,1).last("limit 6");
        //获取热点文章列表
        List<YddArticle> list=yddArticleService.list(yddArticleLQW);
        //初始化返回值列表
        List<YddArticleDto> dataList = new ArrayList<>();
        //封装返回值列表数据
        for (YddArticle yddArticle : list) {
//            Map<String,Object> articleMsg = new HashMap<>();
            YddArticleDto articleDto = new YddArticleDto();
            BeanUtils.copyProperties(yddArticle,articleDto);
            /*articleMsg.put("id",yddArticle.getId());
            articleMsg.put("title",yddArticle.getTitle());
            articleMsg.put("lovenum",yddArticle.getLovenum());
            articleMsg.put("pic",yddArticle.getPic());*/
            //根据文章的分类ID 获取分类名
            YddCate yddCate=yddCateService.getById(yddArticle.getCateid());
            articleDto.setCatename(yddCate.getCatename());
//            articleMsg.put("catename",yddCate.getCatename());
            dataList.add(articleDto);
        }
        R result = new R();
        result.setErrno(0);
        result.putData("desc","侧边最新文章");
        result.putData("list",dataList);

        return result;
    }
    //主页统计信息
    @GetMapping("/baseInfo")
    public ResultData baseInfo() {

        BaseInfoDto baseInfoDto = new BaseInfoDto();

        //1.获取所有分类的数据
        List<YddCate> cateList = yddCateService.list();
        List<YddCateDto> cateDtoList = new ArrayList<>();
        //2.获取分类下对应文章的数量
        for (YddCate yddCate : cateList) {

            YddCateDto yddCateDto = new YddCateDto();
            BeanUtils.copyProperties(yddCate, yddCateDto);
            LambdaQueryWrapper<YddArticle> yddArticleLqw = new LambdaQueryWrapper<>();
            yddArticleLqw.eq(YddArticle::getCateid, yddCate.getId());
            int count = yddArticleService.count(yddArticleLqw);

            yddCateDto.setNum(count);
            cateDtoList.add(yddCateDto);
        }
        baseInfoDto.setAllCate(cateDtoList);

        //获取广告位数量
        baseInfoDto.setAdvposNum(yddAdvposService.count());

        //获取标签总数
        baseInfoDto.setTagNum(yddTagService.count());

        //获取管理员总数
        baseInfoDto.setAdminNum(yddAdvimgService.count());

        //获取文章总数
        baseInfoDto.setArticleNum(yddArticleService.count());

        //获取分类总数
        baseInfoDto.setCateNum(yddCateService.count());

        //获取广告图数量
        baseInfoDto.setAdvimgNum(yddAdvimgService.count());


        //获取最新用户的数据
        LambdaQueryWrapper<YddUser> yddUserLqw = new LambdaQueryWrapper<>();
        //获取最新用户的前七条数据
        yddUserLqw.last("limit 7");
        //2.执行方法查询数据
        List<YddUser> yddUserList = yddUserService.list(yddUserLqw);
        baseInfoDto.setYddUserList(yddUserList);


        //获取是热点文章的数据
        LambdaQueryWrapper<YddArticle> ArticleLqw = new LambdaQueryWrapper<>();
        //1.1查询是否是热点文章
        ArticleLqw.eq(YddArticle::getIshot, 1);
        //1.2根据喜爱收藏进行排序
        ArticleLqw.orderByDesc(YddArticle::getLovenum);
        //1.3查询前七条热点文章的数据
        ArticleLqw.last("limit 7");
        //2.执行方法查询热点文章
        List<YddArticle> yddArticleList = yddArticleService.list(ArticleLqw);
        baseInfoDto.setArticleList(yddArticleList);

        //获取用户数据
        //1.拿到所有用户的数据
        List<YddUser> yddUsers = yddUserService.list();
        //2.创建条件构造器
        LambdaQueryWrapper<YddUser> UserLqw = new LambdaQueryWrapper<>();
        UserLqw.eq(YddUser::getSex, 1);
        List<YddUser> manList = yddUserService.list(UserLqw);
        UserDto userDto = new UserDto();
        userDto.setTotal(yddUsers.size());
        userDto.setUserMan(manList.size());
        userDto.setUserWoman(yddUsers.size() - manList.size());

        baseInfoDto.setUser(userDto);


        return ResultData.ok("", baseInfoDto);

    }
    //new?page=1&limit=10
    @GetMapping("new")
    public ResultData getNew(int page,int limit){
        Page<YddArticle> articlePage = new Page<>(page,limit);
        LambdaQueryWrapper<YddArticle> yddArticleLQW = new LambdaQueryWrapper<>();
        yddArticleLQW.eq(YddArticle::getUserId, UserHolder.getUserId()).orderByDesc(YddArticle::getUpdateDate);
        yddArticleService.page(articlePage,yddArticleLQW);
        PageDto pageDto = PageDto.getPageListDto(articlePage);

        NewArticleDto newArticleDto = new NewArticleDto();
        newArticleDto.setDesc("获取最新文章列表....");
        //清空条件构造器内容
        yddArticleLQW.clear();
        //设置24小时最新文章数量
        //h
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        //获取前一天时间
        calendar.add(Calendar.DAY_OF_YEAR,-1);
        System.out.println(calendar.getTime().toString());
        yddArticleLQW.gt(YddArticle::getUpdateDate, calendar.getTimeInMillis());
        //设置一天内最新文章数量
        newArticleDto.setNum_week(String.valueOf(yddArticleService.count(yddArticleLQW)));

        yddArticleLQW.clear();
        //获取一周前的时间
        calendar.add(Calendar.DAY_OF_YEAR,-6);
        System.out.println(calendar.getTime().toString());
        yddArticleLQW.gt(YddArticle::getUpdateDate, calendar.getTimeInMillis());
        //设置一周最新文章数量
        newArticleDto.setNum_day(String.valueOf(yddArticleService.count(yddArticleLQW)));
        newArticleDto.setList(pageDto);
        return ResultData.ok("",newArticleDto);
    }

    /**
     * 获取推荐文章
     * @return
     */
    @GetMapping("recommend")
    public R recommend(){
        LambdaQueryWrapper<YddArticle> yddArticleLQW = new LambdaQueryWrapper<>();
        //设置热点文章条件
        yddArticleLQW.eq(YddArticle::getIstop,1);
        //获取热点文章列表
        List<YddArticle> list=yddArticleService.list(yddArticleLQW);
        //初始化返回值列表
        List<YddArticleDto> dataList = new ArrayList<>();
        //封装返回值列表数据
        for (YddArticle yddArticle : list) {
            YddArticleDto articleDto = new YddArticleDto();
            BeanUtils.copyProperties(yddArticle,articleDto);
            YddCate yddCate=yddCateService.getById(yddArticle.getCateid());
            articleDto.setCatename(yddCate.getCatename());
            dataList.add(articleDto);
        }
        R result = new R();
        result.setErrno(0);
        result.putData("desc","获取热门文章数据.....");
        result.putData("list",dataList);
        return result;
    }

    //page=1&limit=10&cateid=8
    @GetMapping("list")
    public R list(int page,int limit,String cateid){
        Page<YddArticle> yddArticlePage = new Page<>(page,limit);
        LambdaQueryWrapper<YddArticle> yddArticleLQW = new LambdaQueryWrapper<>();
        yddArticleLQW.eq(YddArticle::getCateid,cateid). //设置获取当前分类 条件
                        eq(YddArticle::getStatus,2) //设置 只获取文章 已发布
                        .orderByDesc(YddArticle::getUpdateDate); //按照时间倒序排序
        yddArticleService.page(yddArticlePage,yddArticleLQW);

        PageDto pageDto = PageDto.getPageListDto(yddArticlePage);

        return R.success("list",pageDto);
    }

    @GetMapping("show")
    public ResultData show(int id){
        //设置查看次数
        YddArticle yddArticle=yddArticleService.getById(id);
        yddArticle.setClick(yddArticle.getClick()+1);
        yddArticleService.updateById(yddArticle);
        //初始化文章信息dto
        YddArticleShowDto yddArticleShowDto = new YddArticleShowDto();
        //设置当前文章的信息
        YddArticle info=yddArticleService.getById(id);
        YddArticleDto yddArticleDto = new YddArticleDto();
        //设置文章分类名
        yddArticleDto.setCatename(yddCateService.getById(info.getCateid()).getCatename());
        BeanUtils.copyProperties(info,yddArticleDto);

        //判断当前用户是否 已经 点赞/收藏  当前文章
        LambdaQueryWrapper<YddUserData> yddUserDataLqw = new LambdaQueryWrapper<>();
        yddUserDataLqw.eq(YddUserData::getUserId,UserHolder.getUserId())
                .eq(YddUserData::getArticleId,id).eq(YddUserData::getType,2);//2代表点赞
        //设置是否点赞
        yddArticleDto.setIsLike(yddUserDataService.getOne(yddUserDataLqw) != null);
        //设置是否收藏
        //清空条件
        yddUserDataLqw.clear();
        yddUserDataLqw.eq(YddUserData::getUserId,UserHolder.getUserId())
                .eq(YddUserData::getArticleId,id).eq(YddUserData::getType,1); //1代表收藏
        yddArticleDto.setIsCollect(yddUserDataService.getOne(yddUserDataLqw) != null);
        yddArticleShowDto.setInfo(yddArticleDto);

        //设置上一篇信息        info.getId()
        List<YddArticle> prev = new ArrayList<>();
        Integer currentId=info.getId();
        Integer nextId = info.getId();
        YddArticle prevYddArticle = null;
        //判断上一篇文章 是否 可用
        do{
            prevYddArticle=yddArticleService.getById(currentId - 1);
            if (prevYddArticle == null && currentId ==0){
                break;
            }
            currentId--;
        }while (prevYddArticle == null || prevYddArticle.getStatus() !=2 );
        //如果上一篇不存在 则设置为当前文章
        info.setTitle("已经到最第一篇!");
        prev.add(prevYddArticle == null ? info:prevYddArticle);
        yddArticleShowDto.setPrev(prev);

        //设置下一篇信息        info.getId()
        List<YddArticle> next = new ArrayList<>();

        //找到最后一篇文章的id
        LambdaQueryWrapper<YddArticle> yddArticleLqw = new LambdaQueryWrapper<>();
        yddArticleLqw.orderByDesc(YddArticle::getCreateDate).last("limit 1");
        YddArticle lastArticle=yddArticleService.getOne(yddArticleLqw);
        YddArticle nextYddArticle = null;
        //判断下一篇文章 是否 可用
        do{
            nextYddArticle=yddArticleService.getById(nextId + 1);
            if (nextYddArticle == null && nextId > lastArticle.getId()){
                break;
            }
            nextId++;
        }while (nextYddArticle == null || nextYddArticle.getStatus() !=2);
        //如果下一篇不存在 则设置为当前文章
        info.setTitle("已经到最后一篇!");
        next.add(nextYddArticle == null ? info:nextYddArticle);
        yddArticleShowDto.setNext(next);

        //获取推荐文章列表  推荐同一分类下的文章
        LambdaQueryWrapper<YddArticle> yddArticleLQW = new LambdaQueryWrapper<>();
        yddArticleLQW.eq(YddArticle::getCateid,info.getCateid()) //获取同一ID下内容 条件
                        .eq(YddArticle::getIshot,1)//推荐文章条件
                                .eq(YddArticle::getStatus,2);//已发布文章
        List<YddArticle> recommendList=yddArticleService.list(yddArticleLQW);
        yddArticleShowDto.setRecommend(recommendList);
        return ResultData.ok("",yddArticleShowDto);
    }
}

